package cn.studyjams.s1.contest.autohello.utils;

/**
 * Created by liuyang
 * on 2016/12/3.
 */

import android.util.Log;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/*
 * Copyright (C) 2013 Surviving with Android (http://www.survivingwithandroid.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public class WeatherHttpClient {

    public String getWeatherData(Double lat, Double lon) {
        HttpURLConnection con = null;
        InputStream is = null;

        try {
            String BASE_URL = "http://api.openweathermap.org/data/2.5/weather?";
            con = (HttpURLConnection) (
                    new URL(BASE_URL + "lat=" +
                            lat + "&lon=" + lon +
                            "&appid=dcf34cdacd7abb5690c299bc56de7809"
                    )
            ).openConnection();
            con.setRequestMethod("GET");
            con.setDoInput(true);
            con.setDoOutput(true);
            con.connect();

            // Let's read the response
            StringBuilder buffer = new StringBuilder();
            is = con.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = br.readLine()) != null)
                buffer.append(line).append("\r\n");

            is.close();
            con.disconnect();
            return buffer.toString();
        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Throwable t) {
                Log.e("WeatherHttpClient", t.toString());
            }

            try {
                if (con != null) {
                    con.disconnect();
                }
            } catch (Throwable t) {
                Log.e("WeatherHttpClient", t.toString());
            }
        }
        return null;
    }
}